Algorithm Search⌘K

Algorithmcore

Laplacian consensus protocol

Also called Olfati-Saber-Murray consensus.

Each agent moves its state toward its neighbors by x' = -L x, which converges to the average on a connected undirected graph.

Time
O(k (r + m)) totalO(r + m) per_round
Space
O(r) extra
Counts
messages O(m) per_round
Where
k = the number of rounds; m = the number of edges; r = the number of agents
Properties
deterministiconlinenot randomized
Origin
Reza Olfati Saber, Richard M. Murray, 2004

The Laplacian consensus protocol lets rr agents that talk only to their neighbors agree on a common value. Each agent ii holds a number xix_i and changes it at the rate x˙i=∑jaij(xj−xi)\dot x_i = \sum_{j} a_{ij} (x_j - x_i), the weighted sum of its differences to its neighbors. For the whole group this is x˙=−Lx\dot x = -L x, where L=D−AL = D - A is the Laplacian matrix of the communication graph. On a fixed, connected, undirected graph every xix_i converges to the average of the initial values, and the slowest part of the error decays as e−λ2te^{-\lambda_2 t}, where λ2\lambda_2 is the second smallest eigenvalue of LL. The sampled form x(k+1)=(I−εL)x(k)x(k+1) = (I - \varepsilon L) x(k) is the same idea in rounds, and it is one standard solution of distributed averaging.

In plain words

Some robots each hold a number, for example a guess of a heading or of a meeting time. No robot sees all the others. Each robot can only read the numbers of the robots near it.

Each robot repeats one small step. It looks at how far each neighbor is above or below its own number, adds up these gaps, and moves its own number a small part of the way in that direction. When the links go both ways with the same weight, what one robot gains its neighbor loses, so the total stays the same. The gaps shrink at every step, so all robots end at the same number, which is the mean of the start values.

If the links go one way only, the robots still agree when the network is well joined, but the common value can favor some robots over others.

The problem

The model. There are rr agents, numbered 11 to rr, and a graph G=(V,E)G = (V, E) with mm edges. A weight aij>0a_{ij} > 0 means that agent ii reads the state of agent jj; this is the convention of Olfati-Saber and Murray, with the neighbors Ni={j:(i,j)∈E}N_i = \{j : (i, j) \in E\}. The graph is undirected when aij=ajia_{ij} = a_{ji}, and directed otherwise. DD is the diagonal matrix of the weighted in-degrees di=∑jaijd_i = \sum_j a_{ij}, and Δ=max⁡idi\Delta = \max_i d_i. The main case on this page is a fixed graph. In the sampled protocol the time is synchronous: in each round every agent reads the current states of its neighbors, and all agents update at the same time.

Input. The graph with its weights, the initial states x(0)∈Rrx(0) \in \mathbb{R}^r, a step ε\varepsilon with 0<ε<1/Δ0 < \varepsilon < 1/\Delta, and a number KK of rounds. For vector states, such as positions in the plane, the protocol runs on each coordinate separately.

Output. The states x(K)x(K). The goal is agreement, xi=xjx_i = x_j for all i,ji, j, and on an undirected connected graph, average consensus, xi→xˉ=1r∑jxj(0)x_i \to \bar x = \frac1r \sum_j x_j(0).

How it differs from close pages. Distributed averaging is the problem; this protocol is one solution, with the weight matrix W=I−εLW = I - \varepsilon L. Gossip averaging solves the same problem with random pairwise exchanges instead of synchronous rounds. The consensus problem of distributed computing is a different problem: processes must decide on one of the proposed values in finite time while some of them crash or lie, and results such as FLP impossibility and protocols such as Paxos belong to it. The Laplacian protocol assumes no faults and reaches agreement only in the limit.

The algorithm

  1. CONSENSUS(G, a, x(0), ε, K)
  2. 1each agent i learns its neighbors N_i and the weights a_ij
  3. 2for k = 0 to K - 1 do
  4. 3for each agent i, in parallel, do
  5. 4u_i ← Σ_{j ∈ N_i} a_ij (x_j(k) - x_i(k)) ▷ only the states of neighbors
  6. 5x_i(k+1) ← x_i(k) + ε u_i
  7. 6all agents switch to the new states at the same time
  8. 7return x(K)

Line L4 is the control input of the continuous protocol x˙i=ui\dot x_i = u_i, and lines L4 and L5 together are one step of the explicit Euler method with step ε\varepsilon. In matrix form a round is x(k+1)=(I−εL)x(k)x(k+1) = (I - \varepsilon L) x(k). The condition ε<1/Δ\varepsilon < 1/\Delta makes every diagonal entry 1−εdi1 - \varepsilon d_i of I−εLI - \varepsilon L positive, so each new state is a convex combination of the old states of the agent and its neighbors. The implementation also has a version that integrates x˙=−Lx\dot x = -L x with the classic fourth order Runge-Kutta method and a fixed step, and a version that uses a different edge set in each round.

Example

Path of three agents. Agents 1, 2 and 3 form the path 1 - 2 - 3 with unit weights. Then

L=(1−10−12−10−11),L = \begin{pmatrix} 1 & -1 & 0 \\ -1 & 2 & -1 \\ 0 & -1 & 1 \end{pmatrix},

with eigenvalues 0, 1 and 3 and eigenvectors (1,1,1)(1, 1, 1), (1,0,−1)(1, 0, -1) and (1,−2,1)(1, -2, 1). The start x(0)=(0,3,6)x(0) = (0, 3, 6) has the average 3, and its error (−3,0,3)(-3, 0, 3) is an eigenvector of the eigenvalue 1. So the continuous protocol gives exactly x(t)=(3−3e−t,3,3+3e−t)x(t) = (3 - 3 e^{-t}, 3, 3 + 3 e^{-t}), and the sampled protocol with ε=1/4\varepsilon = 1/4 multiplies the error by 1−1/4=3/41 - 1/4 = 3/4 in each round: x(1)=(0.75,3,5.25)x(1) = (0.75, 3, 5.25), x(2)=(1.3125,3,4.6875)x(2) = (1.3125, 3, 4.6875).

Two modes. The start x(0)=(0,0,9)x(0) = (0, 0, 9) also has the average 3. Its error (−3,−3,6)(-3, -3, 6) is −4.5(1,0,−1)+1.5(1,−2,1)-4.5 (1, 0, -1) + 1.5 (1, -2, 1), so

x(t)=3⋅1−4.5e−t(1,0,−1)+1.5e−3t(1,−2,1).x(t) = 3 \cdot \mathbf 1 - 4.5 e^{-t} (1, 0, -1) + 1.5 e^{-3t} (1, -2, 1).
tt (s) x1x_1 x2x_2 x3x_3
0 0 0 9
0.5 0.6053 2.3306 6.0641
1 1.4192 2.8506 4.7301
2 2.3947 2.9926 3.6127
4 2.9176 3.0000 3.0824

The fast mode e−3te^{-3t} is gone after about one second. After that the middle agent sits near 3 and the two end agents approach 3 from both sides at the rate e−te^{-t} of λ2=1\lambda_2 = 1. The sampled protocol with ε=1/4\varepsilon = 1/4 gives x(1)=(0,2.25,6.75)x(1) = (0, 2.25, 6.75), x(2)=(0.5625,2.8125,5.625)x(2) = (0.5625, 2.8125, 5.625) and x(4)=(1.5820,2.9883,4.4297)x(4) = (1.5820, 2.9883, 4.4297), and the sum stays 9 in every round.

One-way links. On the directed chain where agent 2 reads agent 1 and agent 3 reads agent 2, agent 1 reads nobody. With x(0)=(5,−1,2)x(0) = (5, -1, 2) and ε=1/2\varepsilon = 1/2, the rounds give (5,2,0.5)(5, 2, 0.5), (5,3.5,1.25)(5, 3.5, 1.25), (5,4.25,2.375)(5, 4.25, 2.375), and all agents converge to 5, the value of the root. The average 2 is not reached, because the graph is not balanced.

Correctness

The proof shows that L1=0L \mathbf 1 = 0, so agreement is an equilibrium, and that on an undirected graph the sum 1Tx\mathbf 1^T x never changes. With the identity xTLx=∑{i,j}aij(xi−xj)2x^T L x = \sum_{\{i,j\}} a_{ij} (x_i - x_j)^2, the error e=x−xˉ1e = x - \bar x \mathbf 1 of the continuous protocol obeys ∥e(t)∥≤e−λ2t∥e(0)∥\lVert e(t) \rVert \le e^{-\lambda_2 t} \lVert e(0) \rVert on a connected graph. For the sampled protocol with 0<ε<1/Δ0 < \varepsilon < 1/\Delta, the error shrinks by the factor ρ=max⁡(∣1−ελ2∣,∣1−ελr∣)<1\rho = \max(|1 - \varepsilon \lambda_2|, |1 - \varepsilon \lambda_r|) < 1 per round, because the Gershgorin circle theorem gives λr≤2Δ\lambda_r \le 2 \Delta. On a strongly connected directed graph, I−εLI - \varepsilon L is a primitive stochastic matrix, and the Perron-Frobenius theorem gives the limit (wTx(0))1(w^T x(0)) \mathbf 1, where ww is the positive left kernel vector of LL with 1Tw=1\mathbf 1^T w = 1. This is the average for every start if and only if the graph is balanced.

Proof: The Laplacian consensus protocol converges to the average on a connected undirected graph, and to a weighted average on a strongly connected directed graphfull

There are rr agents with states xi∈Rx_i \in \mathbb{R}. The weights aij≥0a_{ij} \ge 0 form the matrix AA, with aii=0a_{ii} = 0, and aij>0a_{ij} > 0 exactly when agent ii reads the state of agent jj. The Laplacian is L=D−AL = D - A, where DD is the diagonal matrix of the weighted in-degrees di=∑jaijd_i = \sum_j a_{ij}, and Δ=max⁡idi\Delta = \max_i d_i. The graph is fixed. The continuous protocol is x˙=−Lx\dot x = -L x. The sampled protocol of lines L1 to L7 on the Laplacian consensus protocol page is x(k+1)=Px(k)x(k+1) = P x(k) with P=I−εLP = I - \varepsilon L. 1\mathbf 1 is the all ones vector and xˉ=1r1Tx(0)\bar x = \frac1r \mathbf 1^T x(0).

Lemma 1 (agreement is an equilibrium). L1=0L \mathbf 1 = 0, so every vector c1c \mathbf 1 is an equilibrium of both protocols.

Proof. Row ii of L1L \mathbf 1 is di−∑jaij=0d_i - \sum_j a_{ij} = 0. □\square

Lemma 2 (the sum is invariant on an undirected graph). If AA is symmetric, then 1TL=0\mathbf 1^T L = 0, so 1Tx\mathbf 1^T x is constant along both protocols, and the average stays xˉ\bar x.

Proof. 1TL=(LT1)T=(L1)T=0\mathbf 1^T L = (L^T \mathbf 1)^T = (L \mathbf 1)^T = 0 by Lemma 1. Then ddt1Tx=−1TLx=0\frac{d}{dt} \mathbf 1^T x = -\mathbf 1^T L x = 0, and 1Tx(k+1)=1Tx(k)−ε1TLx(k)=1Tx(k)\mathbf 1^T x(k+1) = \mathbf 1^T x(k) - \varepsilon \mathbf 1^T L x(k) = \mathbf 1^T x(k). □\square

Lemma 3 (the quadratic form). If AA is symmetric, then xTLx=∑{i,j}aij(xi−xj)2x^T L x = \sum_{\{i,j\}} a_{ij} (x_i - x_j)^2, where the sum is over unordered pairs. So LL is symmetric positive semidefinite, and Lx=0L x = 0 if and only if xx is constant on each connected component of the graph.

Proof. xTLx=∑idixi2−∑i,jaijxixj=12∑i,jaij(xi2+xj2−2xixj)x^T L x = \sum_i d_i x_i^2 - \sum_{i,j} a_{ij} x_i x_j = \frac12 \sum_{i,j} a_{ij} (x_i^2 + x_j^2 - 2 x_i x_j), using aij=ajia_{ij} = a_{ji}, and this is the sum over unordered pairs of aij(xi−xj)2≥0a_{ij} (x_i - x_j)^2 \ge 0. For a symmetric positive semidefinite LL, Lx=0L x = 0 if and only if xTLx=0x^T L x = 0, that is, xi=xjx_i = x_j on every edge, that is, xx is constant along every path. □\square

So on a connected undirected graph the eigenvalues of LL are 0=λ1<λ2≤⋯≤λr0 = \lambda_1 < \lambda_2 \le \dots \le \lambda_r, and the kernel is spanned by 1\mathbf 1. The number λ2\lambda_2 is the algebraic connectivity.

Lemma 4 (a bound on the largest eigenvalue). λr≤2Δ\lambda_r \le 2 \Delta.

Proof. By the Gershgorin circle theorem, every eigenvalue lies in a disk with center did_i and radius ∑j≠i∣−aij∣=di\sum_{j \ne i} |{-a_{ij}}| = d_i, so it is at most 2di≤2Δ2 d_i \le 2 \Delta. □\square

Theorem 1 (continuous time, undirected). On a connected undirected graph, the error e(t)=x(t)−xˉ1e(t) = x(t) - \bar x \mathbf 1 of x˙=−Lx\dot x = -L x satisfies ∥e(t)∥2≤e−λ2t∥e(0)∥2\lVert e(t) \rVert_2 \le e^{-\lambda_2 t} \lVert e(0) \rVert_2. So every xi(t)x_i(t) converges to xˉ\bar x exponentially.

Proof. By Lemma 2, 1Te(t)=0\mathbf 1^T e(t) = 0 for all tt, and by Lemma 1, e˙=x˙=−Lx=−Le\dot e = \dot x = -L x = -L e. For a symmetric LL and e⊥1e \perp \mathbf 1, the Rayleigh quotient gives eTLe≥λ2∥e∥2e^T L e \ge \lambda_2 \lVert e \rVert^2, since 1\mathbf 1 spans the eigenspace of λ1=0\lambda_1 = 0. So ddt∥e∥2=−2eTLe≤−2λ2∥e∥2\frac{d}{dt} \lVert e \rVert^2 = -2 e^T L e \le -2 \lambda_2 \lVert e \rVert^2, and Gronwall's inequality gives ∥e(t)∥2≤e−2λ2t∥e(0)∥2\lVert e(t) \rVert^2 \le e^{-2 \lambda_2 t} \lVert e(0) \rVert^2. □\square

Theorem 2 (sampled protocol, undirected). On a connected undirected graph with 0<ε<1/Δ0 < \varepsilon < 1/\Delta, the error of the sampled protocol satisfies ∥e(k)∥2≤ρk∥e(0)∥2\lVert e(k) \rVert_2 \le \rho^k \lVert e(0) \rVert_2 with ρ=max⁡(∣1−ελ2∣,∣1−ελr∣)<1\rho = \max(|1 - \varepsilon \lambda_2|, |1 - \varepsilon \lambda_r|) < 1.

Proof. As in Theorem 1, e(k+1)=(I−εL)e(k)e(k+1) = (I - \varepsilon L) e(k) and e(k)⊥1e(k) \perp \mathbf 1. The symmetric matrix I−εLI - \varepsilon L maps the subspace 1⊥\mathbf 1^\perp to itself, and on it its eigenvalues are 1−ελi1 - \varepsilon \lambda_i for i=2,…,ri = 2, \dots, r. Its norm there is the largest of their absolute values, which is ρ\rho, since 1−ελ1 - \varepsilon \lambda is monotone in λ\lambda. Now λ2>0\lambda_2 > 0 gives 1−ελ2<11 - \varepsilon \lambda_2 < 1, and Lemma 4 gives 1−ελr≥1−2εΔ>−11 - \varepsilon \lambda_r \ge 1 - 2 \varepsilon \Delta > -1. Both values lie in (−1,1)(-1, 1), so ρ<1\rho < 1. □\square

Corollary (disconnected graphs). If the undirected graph has several connected components, the protocol runs on each component on its own, because LL is block diagonal after a renumbering of the agents. By Theorems 1 and 2, each component converges to the average of its own initial states.

Theorem 3 (directed graph). Let the directed graph be strongly connected, and let 0<ε<1/Δ0 < \varepsilon < 1/\Delta. Then there is a unique vector ww with wTL=0w^T L = 0, 1Tw=1\mathbf 1^T w = 1, and all wi>0w_i > 0. The sampled protocol converges to (wTx(0))1(w^T x(0)) \mathbf 1. The limit is the plain average xˉ1\bar x \mathbf 1 for every start if and only if the graph is balanced, that is, ∑jaij=∑jaji\sum_j a_{ij} = \sum_j a_{ji} for every ii.

Proof. The entries of P=I−εLP = I - \varepsilon L are pii=1−εdi>0p_{ii} = 1 - \varepsilon d_i > 0 and pij=εaij≥0p_{ij} = \varepsilon a_{ij} \ge 0 for j≠ij \ne i, and every row sums to 1 by Lemma 1. So PP is a row-stochastic matrix. It has the same off-diagonal pattern as AA, so it is irreducible when the graph is strongly connected, and its positive diagonal makes it primitive: if there is a path of length ℓ\ell from ii to jj, then there is a walk of every length m≥ℓm \ge \ell, by waiting at a vertex, so all entries of PmP^{m} are positive for m≥r−1m \ge r - 1. By the Perron-Frobenius theorem for primitive matrices, the eigenvalue 1 of PP is simple and every other eigenvalue has modulus less than 1. Its left eigenvector ww can be scaled to have positive entries and 1Tw=1\mathbf 1^T w = 1, and Pk→1wTP^k \to \mathbf 1 w^T. So x(k)=Pkx(0)→1(wTx(0))x(k) = P^k x(0) \to \mathbf 1 (w^T x(0)). Since wTP=wTw^T P = w^T if and only if wTL=0w^T L = 0, ww is the left kernel vector of LL.

If the graph is balanced, then column jj of LL sums to dj−∑iaij=0d_j - \sum_i a_{ij} = 0, so 1TL=0\mathbf 1^T L = 0, and w=1/rw = \mathbf 1 / r by uniqueness. Conversely, if wTx(0)=xˉw^T x(0) = \bar x for every x(0)x(0), then w=1/rw = \mathbf 1 / r, so 1TL=0\mathbf 1^T L = 0, which is the balance condition. ■\blacksquare

What is not proved here. For the continuous protocol on a directed graph, the same limit wTx(0)w^T x(0) holds under the same hypothesis, by the same Perron argument applied to e−Lte^{-L t}, which is a positive matrix for t>0t > 0. Olfati-Saber and Murray (2004) give these results and the extension to switching balanced graphs with a common Lyapunov function. When the graph is directed and only has a rooted spanning tree, the protocol still reaches agreement, and the limit is a weighted average of the states of the root strongly connected component; Ren and Beard (2005) prove this and the switching case. For switching undirected graphs, agreement holds when the union of the graphs over bounded intervals is connected (Jadbabaie, Lin and Morse 2003). These results are cited on the page and not proved here.

Complexity

  • Per round. Agent ii reads ∣Ni∣|N_i| states and does O(∣Ni∣)O(|N_i|) arithmetic. A round costs O(r+m)O(r + m) operations in total, in the real RAM model, and O(m)O(m) messages, one state per edge and direction. Each agent stores O(1)O(1) numbers besides its neighbor list.
  • Rounds, proved. On a connected undirected graph, KK rounds reduce the error by the factor ρK\rho^K (Theorem 2 of the proof). To reduce it by a factor δ\delta takes K=⌈ln⁡(1/δ)/ln⁡(1/ρ)⌉K = \lceil \ln(1/\delta) / \ln(1/\rho) \rceil rounds. With ε=1/(2Δ)\varepsilon = 1/(2\Delta), ρ=1−λ2/(2Δ)\rho = 1 - \lambda_2 / (2 \Delta) (Lemma 4 of the proof), so KK is about 2Δln⁡(1/δ)/λ22 \Delta \ln(1/\delta) / \lambda_2. On the path of rr agents, λ2=2−2cos⁡(π/r)\lambda_2 = 2 - 2 \cos(\pi / r), which is about π2/r2\pi^2 / r^2, so the path needs Θ(r2log⁡(1/δ))\Theta(r^2 \log(1/\delta)) rounds. On the complete graph, λ2=r\lambda_2 = r and Δ=r−1\Delta = r - 1, so a constant number of rounds per factor suffices.
  • Continuous time. The error decays as e−λ2te^{-\lambda_2 t}, and this rate is attained by an eigenvector of λ2\lambda_2. Better connected graphs have larger λ2\lambda_2 and converge faster.

Properties

  • Distributed. Each agent uses only the states of its neighbors and its own weights. No agent needs rr, the graph or an identifier.
  • Average preserving on undirected and on balanced directed graphs, because 1TL=0\mathbf 1^T L = 0.
  • Linear and time invariant on a fixed graph, so the solution is x(t)=e−Ltx(0)x(t) = e^{-L t} x(0), and the matrix exponential gives exact values.
  • Asymptotic, not finite time. The states agree only in the limit. Agents that must stop need a tolerance.
  • No fault tolerance. One agent that keeps a fixed value pulls every agent to that value, as the root does in the directed example.
  • Deterministic. The same graph and start always give the same states.

Variants and improvements

  • Switching graphs. If the graph changes over time, agreement still holds when the union of the graphs over every interval of bounded length is connected (Jadbabaie, Lin and Morse 2003), or, for directed graphs, has a rooted spanning tree (Ren and Beard 2005).
  • Directed graphs. Agreement holds when the graph has a rooted spanning tree. The limit is the average only on balanced graphs (Olfati-Saber and Murray 2004).
  • Time delays. With a delay τ\tau in every link, the continuous protocol on a fixed undirected graph still converges if τ<π/(2λr)\tau < \pi / (2 \lambda_r) (Olfati-Saber and Murray 2004).
  • Optimal weights. For the sampled protocol, the weights that make ρ\rho smallest are the solution of a semidefinite program (Xiao and Boyd 2004), see distributed averaging.
  • Second order consensus and flocking. Agents with double integrator dynamics run the protocol on the velocities and a related rule on the positions, which gives velocity agreement as in boids.
  • Leader following. One agent with fixed state and a graph with a rooted spanning tree make all agents converge to the leader, as in the directed example.

When to use it

Use the protocol when agents must agree on one number or vector, such as a heading, a speed, a clock offset or the center of the group, and each agent can talk only to its neighbors. It is the building block of rendezvous for agents that stay connected and of displacement-based formation control, where agents agree on xi−cix_i - c_i for given offsets cic_i. Use gossip averaging when links fire at random times, and use a fault tolerant agreement protocol when agents can crash or lie.

Pitfalls

  • Step size. The sampled protocol needs ε<1/Δ\varepsilon < 1/\Delta for the convex combination, and diverges when ελr>2\varepsilon \lambda_r > 2. On the path of three agents with ε=0.9\varepsilon = 0.9, the mode (1,−2,1)(1, -2, 1) is multiplied by 1−2.7=−1.71 - 2.7 = -1.7 in each round.
  • Direction of the edges. Some texts write aij>0a_{ij} > 0 when jj reads ii. Then LL is the transpose, and the condition on the graph changes from in-degrees to out-degrees. State the convention.
  • Directed graphs do not average. On an unbalanced directed graph the limit is a weighted average, and on a graph without a rooted spanning tree there is no agreement at all.
  • Disconnected graphs. Each connected component agrees on its own average. The protocol cannot detect that the graph is disconnected.
  • Moving robots. When the states are positions and the graph depends on distances, the motion can break edges. The protocol alone does not keep the graph connected; see connectivity maintenance.
  • Not the fault tolerant consensus. The name is the same as the consensus problem of distributed computing, but the guarantees are not.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

laplacian_consensus_protocol.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/laplacian-consensus-protocol/. The authors are listed in prov/GHGHQ7.jsonl.

"""Laplacian consensus protocol x' = -L x and its sampled form x(k+1) = (I - eps L) x(k).

Agents are 0..r-1. An edge (i, j) or (i, j, w) means that agent i receives the
state of agent j with weight w > 0 (a_ij = w). For an undirected graph the edge
also gives a_ji = w. This is the convention of Olfati-Saber and Murray (2004):
the neighbors of i are the agents j with (i, j) in E.
"""

from typing import Sequence

Edge = tuple  # (i, j) or (i, j, w)


def adjacency(r: int, edges: Sequence[Edge], directed: bool = False) -> list[list]:
    """Return the weighted adjacency matrix A with A[i][j] = a_ij."""
    a = [[0] * r for _ in range(r)]
    for e in edges:
        i, j = e[0], e[1]
        w = e[2] if len(e) > 2 else 1
        if i == j:
            raise ValueError("self loops are not allowed")
        if w <= 0:
            raise ValueError("weights must be positive")
        a[i][j] += w
        if not directed:
            a[j][i] += w
    return a


def laplacian(r: int, edges: Sequence[Edge], directed: bool = False) -> list[list]:
    """Return L = D - A, where D holds the weighted in-degrees (row sums of A)."""
    a = adjacency(r, edges, directed)
    lap = [[-a[i][j] for j in range(r)] for i in range(r)]
    for i in range(r):
        lap[i][i] = sum(a[i])
    return lap


def neighbor_lists(r: int, edges: Sequence[Edge], directed: bool = False) -> list[list]:
    """Return, for each agent i, the list of pairs (j, a_ij) with a_ij > 0."""
    a = adjacency(r, edges, directed)
    return [[(j, a[i][j]) for j in range(r) if a[i][j] != 0] for i in range(r)]


def consensus_step(nbrs: list[list], x: Sequence, eps) -> list:
    """One synchronous round of the sampled protocol. Each agent reads only its neighbors."""
    new = []
    for i in range(len(x)):  # @line L3
        u = sum(w * (x[j] - x[i]) for j, w in nbrs[i])  # @line L4
        new.append(x[i] + eps * u)  # @line L5
    return new


def discrete_consensus(r: int, edges: Sequence[Edge], x0: Sequence, eps, steps: int,
                       directed: bool = False) -> list:
    """Run x(k+1) = (I - eps L) x(k) for the given number of rounds.

    The protocol is stable for 0 < eps < 1 / Delta, where Delta is the largest
    weighted in-degree. Works with float or fractions.Fraction values.
    """
    nbrs = neighbor_lists(r, edges, directed)  # @line L1
    x = list(x0)
    for _ in range(steps):  # @line L2
        x = consensus_step(nbrs, x, eps)  # @line L6
    return x  # @line L7


def switching_consensus(r: int, edge_sets: Sequence[Sequence[Edge]], x0: Sequence, eps,
                        steps: int, directed: bool = False) -> list:
    """Sampled protocol on a switching graph: round k uses edge_sets[k mod len(edge_sets)]."""
    lists = [neighbor_lists(r, es, directed) for es in edge_sets]
    x = list(x0)
    for k in range(steps):
        x = consensus_step(lists[k % len(lists)], x, eps)
    return x


def continuous_consensus(r: int, edges: Sequence[Edge], x0: Sequence[float], t: float,
                         dt: float, directed: bool = False) -> list[float]:
    """Integrate x' = -L x from 0 to t with the classic RK4 method and fixed step dt."""
    lap = laplacian(r, edges, directed)

    def f(x):
        return [-sum(lap[i][j] * x[j] for j in range(r)) for i in range(r)]

    x = [float(v) for v in x0]
    steps = max(1, round(t / dt))
    h = t / steps
    for _ in range(steps):
        k1 = f(x)
        k2 = f([x[i] + 0.5 * h * k1[i] for i in range(r)])
        k3 = f([x[i] + 0.5 * h * k2[i] for i in range(r)])
        k4 = f([x[i] + h * k3[i] for i in range(r)])
        x = [x[i] + h / 6 * (k1[i] + 2 * k2[i] + 2 * k3[i] + k4[i]) for i in range(r)]
    return x


def max_degree(r: int, edges: Sequence[Edge], directed: bool = False):
    """Return Delta, the largest weighted in-degree."""
    return max(sum(row) for row in adjacency(r, edges, directed))
test_laplacian_consensus_protocol.py 162 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/laplacian-consensus-protocol/. The authors are listed in prov/GHGHQ7.jsonl.

import math
import random
from fractions import Fraction

from laplacian_consensus_protocol import (
    continuous_consensus,
    discrete_consensus,
    laplacian,
    max_degree,
    switching_consensus,
)

PATH3 = [(0, 1), (1, 2)]


def random_connected(rng: random.Random, r: int, extra: int) -> list:
    edges = [(i, rng.randrange(i), rng.choice([1, 2, 3])) for i in range(1, r)]
    for _ in range(extra):
        i, j = rng.sample(range(r), 2)
        edges.append((i, j, rng.choice([1, 2, 3])))
    return edges


def solve_left_kernel(lap: list) -> list:
    """Brute force: solve w^T L = 0 with sum(w) = 1 by exact Gaussian elimination."""
    r = len(lap)
    rows = [[Fraction(lap[i][j]) for i in range(r)] + [Fraction(0)] for j in range(r)]
    rows[-1] = [Fraction(1)] * r + [Fraction(1)]
    for c in range(r):
        p = next(k for k in range(c, r) if rows[k][c] != 0)
        rows[c], rows[p] = rows[p], rows[c]
        for k in range(r):
            if k != c and rows[k][c] != 0:
                f = rows[k][c] / rows[c][c]
                rows[k] = [a - f * b for a, b in zip(rows[k], rows[c])]
    return [rows[i][r] / rows[i][i] for i in range(r)]


def test_laplacian_path3() -> None:
    assert laplacian(3, PATH3) == [[1, -1, 0], [-1, 2, -1], [0, -1, 1]]
    # trace 4 = 0 + 1 + 3, and the sum of the 2x2 principal minors 3 = 0*1 + 0*3 + 1*3
    lap = laplacian(3, PATH3)
    assert sum(lap[i][i] for i in range(3)) == 4
    minors = sum(lap[i][i] * lap[j][j] - lap[i][j] * lap[j][i] for i in range(3) for j in range(i + 1, 3))
    assert minors == 3


def test_path3_discrete_exact() -> None:
    eps = Fraction(1, 4)
    for k in range(6):
        x = discrete_consensus(3, PATH3, [0, 3, 6], eps, k)
        d = 3 * Fraction(3, 4) ** k
        assert x == [3 - d, 3, 3 + d]


def test_path3_continuous_closed_form() -> None:
    for t in (0.5, 1.0, 3.0):
        x = continuous_consensus(3, PATH3, [0, 3, 6], t, 0.01)
        want = [3 - 3 * math.exp(-t), 3, 3 + 3 * math.exp(-t)]
        assert max(abs(a - b) for a, b in zip(x, want)) < 1e-9


def test_sum_is_invariant_on_undirected_graphs() -> None:
    rng = random.Random(1)
    for _ in range(40):
        r = rng.randrange(2, 8)
        edges = random_connected(rng, r, rng.randrange(4))
        eps = Fraction(1, 2 * max_degree(r, edges))
        x0 = [Fraction(rng.randrange(-20, 21)) for _ in range(r)]
        for k in (1, 2, 5):
            assert sum(discrete_consensus(r, edges, x0, eps, k)) == sum(x0)


def test_converges_to_average() -> None:
    rng = random.Random(2)
    for _ in range(40):
        r = rng.randrange(2, 9)
        edges = random_connected(rng, r, rng.randrange(5))
        eps = 0.9 / max_degree(r, edges)
        x0 = [rng.uniform(-10, 10) for _ in range(r)]
        avg = sum(x0) / r
        x = discrete_consensus(r, edges, x0, eps, 4000)
        assert max(abs(v - avg) for v in x) < 1e-6


def test_rate_on_path_graphs() -> None:
    # Path with r nodes: eigenvalues 2 - 2 cos(k pi / r). With eps = 1/4 the error
    # contracts by rho = max |1 - eps lambda| over the nonzero eigenvalues.
    rng = random.Random(3)
    for r in (3, 5, 8):
        edges = [(i, i + 1) for i in range(r - 1)]
        lams = [2 - 2 * math.cos(k * math.pi / r) for k in range(1, r)]
        rho = max(abs(1 - 0.25 * lam) for lam in lams)
        x0 = [rng.uniform(-5, 5) for _ in range(r)]
        avg = sum(x0) / r
        e0 = math.sqrt(sum((v - avg) ** 2 for v in x0))
        for k in (5, 20, 60):
            x = discrete_consensus(r, edges, x0, 0.25, k)
            ek = math.sqrt(sum((v - avg) ** 2 for v in x))
            assert ek <= rho ** k * e0 * (1 + 1e-9) + 1e-12


def test_disconnected_graph_gives_component_averages() -> None:
    edges = [(0, 1), (2, 3), (3, 4)]
    x = discrete_consensus(5, edges, [0.0, 4.0, 1.0, 2.0, 6.0], 0.3, 3000)
    want = [2.0, 2.0, 3.0, 3.0, 3.0]
    assert max(abs(a - b) for a, b in zip(x, want)) < 1e-9


def test_directed_limit_is_left_eigenvector_average() -> None:
    rng = random.Random(4)
    for _ in range(25):
        r = rng.randrange(3, 7)
        # a directed cycle makes the graph strongly connected; add random chords
        edges = [(i, (i + 1) % r, rng.choice([1, 2])) for i in range(r)]
        for _ in range(rng.randrange(4)):
            i, j = rng.sample(range(r), 2)
            edges.append((i, j, rng.choice([1, 2, 3])))
        lap = laplacian(r, edges, directed=True)
        w = solve_left_kernel(lap)
        assert all(v > 0 for v in w)
        x0 = [rng.uniform(-5, 5) for _ in range(r)]
        want = sum(float(wi) * xi for wi, xi in zip(w, x0))
        eps = 0.9 / max_degree(r, edges, directed=True)
        x = discrete_consensus(r, edges, x0, eps, 5000, directed=True)
        assert max(abs(v - want) for v in x) < 1e-6


def test_directed_leader_follower_chain() -> None:
    # agent 0 hears nobody, 1 hears 0, 2 hears 1: a rooted spanning tree.
    edges = [(1, 0), (2, 1)]
    x = discrete_consensus(3, edges, [5.0, -1.0, 2.0], 0.5, 200, directed=True)
    assert max(abs(v - 5.0) for v in x) < 1e-9


def test_balanced_directed_graph_gives_average() -> None:
    edges = [(0, 1), (1, 2), (2, 3), (3, 0)]
    x0 = [1.0, 7.0, -2.0, 6.0]
    x = discrete_consensus(4, edges, x0, 0.5, 400, directed=True)
    assert max(abs(v - 3.0) for v in x) < 1e-9


def test_switching_union_connected() -> None:
    # Each graph alone is disconnected, but their union is the path 0-1-2-3.
    sets = [[(0, 1), (2, 3)], [(1, 2)]]
    x0 = [Fraction(8), Fraction(0), Fraction(4), Fraction(0)]
    assert switching_consensus(4, sets, x0, Fraction(1, 2), 1) == [4, 4, 2, 2]
    x = switching_consensus(4, sets, x0, Fraction(1, 2), 2)
    assert x == [4, 3, 3, 2]
    assert sum(x) == sum(x0)
    xf = switching_consensus(4, sets, [8.0, 0.0, 4.0, 0.0], 0.4, 400)
    assert max(abs(v - 3.0) for v in xf) < 1e-9


def test_large_step_diverges() -> None:
    # eps above 2 / lambda_max breaks the protocol: lambda_max = 3 on the path P3.
    # The start (0, 6, 0) has its error (-2, 4, -2) along the eigenvector of 3.
    x = discrete_consensus(3, PATH3, [0.0, 6.0, 0.0], 0.9, 30)
    assert abs(x[0] - 2.0) > 1.0

History

In 2003 Jadbabaie, Lin and Morse proved that the nearest neighbor heading rule from the flocking model of Vicsek et al. (1995) reaches agreement when the graph is connected often enough. In 2004 Olfati-Saber and Murray stated the protocol x˙=−Lx\dot x = -L x for networks of agents, proved average consensus on balanced directed graphs, and treated switching graphs and delays. Ren and Beard extended the results to directed graphs with a spanning tree in 2005. The survey of Olfati-Saber, Fax and Murray (2007) and the book of Mesbahi and Egerstedt (2010) give the theory in one place.

References

  1. Reza Olfati-Saber and Richard M. Murray, Consensus problems in networks of agents with switching topology and time-delays, IEEE Transactions on Automatic Control 49(9), 2004, pages 1520 to 1533 (the protocol, average consensus on balanced and strongly connected digraphs, switching topology and delays)
  2. Ali Jadbabaie, Jie Lin and A. Stephen Morse, Coordination of groups of mobile autonomous agents using nearest neighbor rules, IEEE Transactions on Automatic Control 48(6), 2003, pages 988 to 1001 (agreement of headings when the union of the graphs over bounded intervals is connected)
  3. Wei Ren and Randal W. Beard, Consensus seeking in multiagent systems under dynamically changing interaction topologies, IEEE Transactions on Automatic Control 50(5), 2005, pages 655 to 661 (consensus on directed graphs that have a spanning tree)
  4. Reza Olfati-Saber, J. Alex Fax and Richard M. Murray, Consensus and cooperation in networked multi-agent systems, Proceedings of the IEEE 95(1), 2007, pages 215 to 233 (survey of the continuous and discrete protocols and their convergence rates)
  5. Mehran Mesbahi and Magnus Egerstedt, Graph Theoretic Methods in Multiagent Networks, Princeton University Press, 2010, Chapter 3, The Agreement Protocol, Part I (Section 3.1 for undirected and Section 3.2 for directed graphs)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.per_round
  • a full proof of time.total
  • a full proof of space.extra
  • a full proof of messages.per_round
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example